package com.relytosoft.mizar.media.common.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import com.relytosoft.mizar.media.common.config.SSLSocketClient;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.net.ssl.X509TrustManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * @author wss
 * @version 1.0
 * @date 2022/5/16 17:50
 */
public class ImageUtil {

    /**
     * base64字符串转图片
     *
     * @param imgStr
     * @return
     */
    public static byte[] GenerateImage(String imgStr) {
        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) {
            //图像数据为空
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        //图片的输出流
        OutputStream imageOut = null;
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
            }
            return b;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 图片转base64字符串
     *
     * @param imgFilePath
     * @return
     */
    public static String GetImageStr(String imgFilePath) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    /**
     * 通过url获取流
     *
     * @param url
     * @return
     */
    public static byte[] urlToBytes(String url) {
        InputStream inputStream = URLUtil.getStream(URLUtil.url(url));
        return IoUtil.readBytes(inputStream);
    }

    /**
     * 图片画框
     *
     * @param inputStream 输入流
     * @param leftBottomX 左下x
     * @param leftBottomY 左下y
     * @param rightTopX   右上x
     * @param rightTopY   右上y
     * @return
     */
    public static byte[] imageFrame(InputStream inputStream, int leftBottomX, int leftBottomY, int rightTopX, int rightTopY) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            g2D.setColor(Color.RED);
            g2D.setStroke(new BasicStroke(5));
            g2D.drawRect(leftBottomX, leftBottomY, rightTopX - leftBottomX, rightTopY - leftBottomY);
            g2D.setFont(new Font("", Font.BOLD, 40));
            g2D.drawString("目标对象", leftBottomX + 10, leftBottomY + 60);
            ImageIO.write(bufferedImage, "jpg", baos);
            baos.flush();
            inputStream.close();
            return baos.toByteArray();
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 图片画框
     *
     * @param bytes       byte数组
     * @param leftBottomX 左下x
     * @param leftBottomY 左下y
     * @param rightTopX   右上x
     * @param rightTopY   右上y
     * @return
     */
    public static byte[] imageFrame(byte[] bytes, int leftBottomX, int leftBottomY, int rightTopX, int rightTopY) {
        ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(bytes);
        return imageFrame(byteArrayInputStream, leftBottomX, leftBottomY, rightTopX, rightTopY);
    }

    public static byte[] trustUrlToBytes(String url) {
        InputStream inputStream = null;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        try {
            X509TrustManager manager = SSLSocketClient.getX509TrustManager();
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .sslSocketFactory(SSLSocketClient.getSocketFactory(manager), manager)
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .readTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(120, TimeUnit.SECONDS)
                    .connectionPool(new ConnectionPool())
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .build();
            okhttp3.ResponseBody body = client.newCall(request).execute().body();
            inputStream = body.byteStream();
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            buffer = output.toByteArray();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return buffer;
        }
    }
}
